package com.example.yls.demoa;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btnSave;
    private Button btnRead;
    private EditText edtName;
    private EditText edtAge;
    private RadioButton radioBoy;
    private RadioButton radioGirl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*edtName = findViewById(R.id.edt_name);
        edtAge = findViewById(R.id.edt_age);
        radioBoy = findViewById(R.id.radio_isboy);
        radioGirl = findViewById(R.id.radio_noboy);

        String name = edtName.getText().toString();
        int age = Integer.valueOf(edtAge.getText().toString()).intValue() ;
        Log.e("!!!!!",""+age+"");*/

        btnSave = findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sp = getSharedPreferences("student", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("isBoy",true);
                editor.putString("name","King");
                editor.putInt("age",26);
                editor.commit();

            }
        });

        btnRead = findViewById(R.id.btn_read);
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sp = getSharedPreferences("student", Context.MODE_PRIVATE);
                String name = sp.getString("name","noname");
                int age = sp.getInt("age",0);
                boolean isBoy = sp.getBoolean("isBoy",true);
                Toast.makeText(MainActivity.this,name+" "+age+" "+isBoy,Toast.LENGTH_SHORT).show();
            }
        });



    }

    @Override
    protected void onStart() {
        super.onStart();
        readInfoFromSP();
    }

    private void readInfoFromSP() {
        SharedPreferences sp = getSharedPreferences("student", Context.MODE_PRIVATE);
        String name = sp.getString("name","noname");
        int age = sp.getInt("age",0);
        boolean isBoy = sp.getBoolean("isBoy",true);
        edtName.setText(name);
        edtAge.setText(String.valueOf(age));
        if(isBoy){
            radioBoy.setChecked(true);
        }else {
            radioGirl.setChecked(true);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }
}
